package us.mooresr.aircraftscheduling.client.ui;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.Widget;

public class TimePicker extends Composite {

	private static TimePickerUiBinder uiBinder = GWT
			.create(TimePickerUiBinder.class);

	interface TimePickerUiBinder extends UiBinder<Widget, TimePicker> {
	}
	
	@UiField
	ListBox hourControl;
	
	@UiField
	ListBox minuteControl;
	
	@UiField
	ListBox  ampmControl;

	public TimePicker() {
		initWidget(uiBinder.createAndBindUi(this));
		
		hourControl.addItem("1");
		hourControl.addItem("2");
		hourControl.addItem("3");
		hourControl.addItem("4");
		hourControl.addItem("5");
		hourControl.addItem("6");
		hourControl.addItem("7");
		hourControl.addItem("8");
		hourControl.addItem("9");
		hourControl.addItem("10");
		hourControl.addItem("11");
		hourControl.addItem("12");
		
		minuteControl.addItem("00");
		minuteControl.addItem("30");
		
		ampmControl.addItem("am");
		ampmControl.addItem("pm");
	}
	
	public int getHour() {
		int hourIndex = hourControl.getSelectedIndex();
		int ampmIndex = ampmControl.getSelectedIndex();
		int result;
		
		if ((hourIndex == 11) && (ampmIndex == 0)) {
			// Special case - 12:00 AM is real zero hours
			result = 0;
		} else {
			result = hourIndex + 1;
			if (ampmIndex == 1) {
				result += 12;
			}
		}
		
		return result;
	}
	
	public int getMinute() {
		if (minuteControl.getSelectedIndex() == 0) {
			return 0;
		} else {
			return 30;
		}
	}
	
	public void setHour(int hour) {
		if ((hour < 0) || (hour > 23)) {
			return;
		}
		
		if (hour > 11) {
			ampmControl.setSelectedIndex(1);
		} else {
			ampmControl.setSelectedIndex(0);
		}
		
		//
		//     hour     index
		//      0         11        (12:00 AM)
		//      1          0
		//      2          1
		//          ...
		//     12         11        (Noon)
		//     13          0
		//     14          1
		//           ...
		//     23         10        (11:00 PM)
		
		if (hour == 0) {
			hour = 11;
		} else if (hour < 13) {
			hour = hour - 1;
		} else {
			hour = hour - 13;
		}
		
		hourControl.setSelectedIndex(hour);
		
	}
	
	public void setMinute(int minute) {
		if ((minute < 0) || (minute > 59)) {
			return;
		}
		
		if (minute < 30) {
			minuteControl.setSelectedIndex(0);
		} else {
			minuteControl.setSelectedIndex(1);
		}
	}
	
	public void clear() {
		hourControl.setSelectedIndex(0);
		minuteControl.setSelectedIndex(0);
		ampmControl.setSelectedIndex(0);
	}

}
